import { ref, type Ref } from "vue";

type Size = { width: number; height: number };

export type Result = {
    size: Ref<Size>, 
    cancel: () => void 
}

/**
 * @param target 监听尺寸变化的元素
 * @param changeHandel [可选]，尺寸变化时的回调函数
 * @returns { size: Ref<{width, height}>, cancel: () => void }
 */
export function useDomChangeSize(target: HTMLElement, changeHandel?: (size: Size) => unknown): Result {

    let resizeObserver: any;
    function cancel(){
        resizeObserver?.disconnect();
    }

    const size = ref<Size>({ 
        width: target.clientWidth ?? 0, 
        height: target.clientHeight ?? 0
    })
    

    if (target) {
        resizeObserver = new ResizeObserver((entries) => {
            entries.forEach((entry) => {
              const { clientWidth, clientHeight } = entry.target;
              size.value.width = clientWidth
              size.value.height = clientHeight

              if(changeHandel) {
                changeHandel(size.value)
              }

            });
        });
        resizeObserver.observe(target);
    }


    return {
        size,
        cancel
    };
}